package com.msmall.base.message;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MessageManager {

	/**
	 * key : userid
	 * value.key : 序号
	 */
	public static final Map<Long, Map<String, Message>> messages = new ConcurrentHashMap<Long, Map<String,Message>>();
	
	/**
	 * key : userid
	 * value. key :fieldname
	 */
	public static final Map<Long, Map<String, FieldError>> fieldErrors = new ConcurrentHashMap<Long, Map<String, FieldError>>();
	
	public static synchronized void addFieldError(Long userid, FieldError fieldError){
		Map<String, FieldError> map = getFieldErrors(userid);
		if(map == null){
			map = new HashMap<String, FieldError>();
			fieldErrors.put(userid, map);
		}
		map.put(fieldError.getFieldName(), fieldError);
	}
	public static synchronized void addMessage(Long userid, Message message){
		Map<String, Message> map = getMessages(userid);
		if(map == null){
			map = new HashMap<String, Message>();
			messages.put(userid, map);
		}
		map.put(message.getPosition(), message);
	}
	
	public static Map<String, Message> getMessages(Long userid){
		Map<String, Message> map = messages.get(userid);
		return map;
	}
	public static Map<String, FieldError> getFieldErrors(Long userid){
		Map<String, FieldError> map = fieldErrors.get(userid);
		return map;
	}
	public static FieldError getFieldError(Long userid, String fieldName){
		Map<String, FieldError> map = getFieldErrors(userid);
		if(map != null)
			return map.get(fieldName);
		return null;
	}
	public static Message getMessage(Long userid, String position){
		Map<String, Message> map = messages.get(userid);
		if(map != null)
			return map.get(position);
		return null;
	}
	public static void clearMessages(Long userid){
		Map<String, Message> map = messages.get(userid);
		if(map != null){
			messages.remove(userid);
		}
	}
	public static void clearFieldErrors(Long userid){
		Map<String, FieldError> map = fieldErrors.get(userid);
		if(map != null){
			fieldErrors.remove(userid);
		}
	}
}
